import os
from typing import Union

from fastapi import FastAPI, APIRouter
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from app.core import events
from app.admin.main import configure_admin_router
from app.api.main import api_router, configure_router


# 注册事件
def register_event(app: FastAPI):
    app.add_event_handler("startup", events.startup(app))
    app.add_event_handler("shutdown", events.stopping(app))


# 注册中间件
def register_middleware(app: FastAPI):
    origins = ["*"]

    # def configure_middleware(app: FastAPI):
    #     """配置中间件"""
    #     app.add_middleware(
    #         CORSMiddleware,
    #         allow_origins=origins,
    #         allow_credentials=True,
    #         allow_methods=["*"],
    #         allow_headers=["*"],
    #     )

    """配置中间件"""
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 注册静态资源目录
def register_static(app: FastAPI):
    """配置静态资源"""
    from app.core.config import settings
    # 静态资源路径配置
    app.mount('/static', StaticFiles(directory=settings.STATIC_DIR), name="static")
    print(settings.STATIC_DIR)
    # 创建上传路径
    if not os.path.exists(settings.UPLOAD_DIR):
        os.makedirs(settings.UPLOAD_DIR)
    # 配置上传路径
    app.mount('/', StaticFiles(directory=settings.UPLOAD_DIR), name='upload')






# app.include_router(api_router)


def create_app() -> FastAPI:
    from app.exception.global_exception import configure_exception

    app = FastAPI(
        title="Think FastAPI",
        description="A FastAPI application with automatic docs.",
        version="1.0.0",
    )
    # 注册路由
    configure_admin_router(app)
    configure_router(app)
    # 配置全局异常处理
    configure_exception(app)
    # 注册钩子函数
    register_event(app)
    # 注册中间件
    register_middleware(app)
    # 挂载文件夹
    register_static(app)

    return app
